package com.navi.loaddata.loadService.impl.EqEvent;

import com.navi.loaddata.core.mysqlEntity.EtlConfD;
import com.navi.loaddata.core.mysqlEntity.EtlConfDModel;
import com.navi.loaddata.core.oracleEntity.EtlEquipEventV;
import com.navi.loaddata.core.repository.impl.MesRepositoryImpl;
import com.navi.loaddata.core.util.JdbcUtil;
import com.navi.loaddata.core.util.LoggerUtil;
import com.navi.loaddata.core.util.ProcessUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author xufan
 */
@Service
public class LoadEqAlarmService {
    private static final Logger logger = LoggerFactory.getLogger(LoadEqAlarmService.class);
    private LoggerUtil loggerUtil = new LoggerUtil(this.getClass());

    @Autowired
    private SaveEqAlarm saveEqAlarm;
    @Autowired
    private MesRepositoryImpl mesdao;

    public String[] loadEqAlarmDataMain(EtlConfDModel etlConfD) throws Exception {
        String[] resMsg=new String[3];

        try {
            resMsg = loadEqAlarmData(etlConfD);
            String msg=etlConfD.getEqpt();

            if(StringUtils.isEmpty(etlConfD.getOpe())) msg="ALL";
            logger.info("Eqpt={} loadEqAlarmMain finish!",msg);
        } catch (Exception e) {
            throw e;
        }
        return resMsg;
    }

    /**
     * Load Measure Data
     * <p>
     * load base -> session table
     * load defect data  -> session table
     * call base proc  -> auto commit
     * call defect proc -> no auto commit
     * delete defect session table
     *
     * @param etlConfD
     */
    private String[] loadEqAlarmData(EtlConfDModel etlConfD) throws Exception {
        String[] resMsg=new String[3];
        int okCnt = 0;
        int errCnt=0;
        String errMsg=null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start=etlConfD.getRunStartTimestamp().toString().substring(0,19);
        String end=etlConfD.getRunEndTimestamp().toString().substring(0,19);

        Timestamp updateTime = Timestamp.valueOf(LocalDateTime.now());

        QueryRunner qr_gp = JdbcUtil.getQueryRunner_mes();
        QueryRunner qr_ora = JdbcUtil.getQueryRunner_ora_edaldr();
        // gp mes data
        String sql="SELECT" +
                " A.unitname as equipId," +
                " A.eventtime as eventStartTime," +
                " 'EQAL' as eventCategory," +
                " A.alarmcode as eventCode ," +
                " A.alarmlevel as eventGroup ," +
                " A.EventUser as eventUser," +
                " A.eventcomment as eventComment," +
//                " --alarmstate as item4" +
                " A.TIMEKEY as timeKey," +
                " B.SUBFACTORYNAME AS shop" +
                " from mes_ct_machinealarmhistory A" +
                " LEFT JOIN MES_MACHINESPEC B ON A.UNITNAME=B.MACHINENAME" +
                " where 1=1" +
                //没有SHOP OPE
                ProcessUtil.getEqptMesHisHql(etlConfD.getEqpt())+
                " and A.UPDATETIME >= to_date('"+start+"','yyyy-mm-dd hh24:mi:ss') " +
                " AND A.UPDATETIME <  to_date('"+end+"','yyyy-mm-dd hh24:mi:ss')" +
                " AND A.alarmstate='SET'" +
//                " and B.SUBFACTORYNAME<>'ACF'" +
                " and B.SUBFACTORYNAME IS NOT NULL";
        List<EtlEquipEventV> etlEquipEventVList = qr_gp.query(sql, new BeanListHandler<EtlEquipEventV>(EtlEquipEventV.class));
        logger.info("MES 机台概况数据量：{}",etlEquipEventVList.size());

        if(etlEquipEventVList.size()>0) {
            String clearSql = "";
            for(EtlEquipEventV setV:etlEquipEventVList) {
                clearSql = "SELECT " +
                        " CASE WHEN alarmstate='CLEAR' OR ROWNUM<=1 THEN eventtime ELSE NULL END as eventEndTime" +
                        " FROM mes_ct_machinealarmhistory" +
                        " WHERE 1=1" +
                        " and TIMEKEY > '" + setV.getTimeKey() + "'" +
                        " AND alarmstate in('SET','CLEAR')" +
                        " AND rownum=1" +
                        " ORDER BY TIMEKEY ASC";
                List<EtlEquipEventV> clearList = qr_gp.query(clearSql, new BeanListHandler<EtlEquipEventV>(EtlEquipEventV.class));
                if (clearList.size() > 0) {
                    setV.setEventEndTime(clearList.get(0).getEventEndTime());
                }
                logger.info("equipId={} eventCode={} eventStartTime={} 转换成功!",setV.getEquipId(),setV.getEventCode(),sdf.format(setV.getEventStartTime()));
            }

            for(int i=0;i<etlEquipEventVList.size();i+=1000){
                Map<String,EtlEquipEventV> saveList = new HashedMap();
                for(int j=0;j<1000;j++){
                    if(i+j<etlEquipEventVList.size()){
                        if(saveList.size()>0&&null!=saveList.get(etlEquipEventVList.get(i+j).getEquipId()+"_"+etlEquipEventVList.get(i+j).getEventCode()+"_"+etlEquipEventVList.get(i+j).getEventStartTime())){
                            errCnt++;
                            continue;
                        }
                        saveList.put(etlEquipEventVList.get(i+j).getEquipId()+"_"+etlEquipEventVList.get(i+j).getEventCode()+"_"+etlEquipEventVList.get(i+j).getEventStartTime(),etlEquipEventVList.get(i+j));
                        okCnt++;
                    }
                }
                saveEqAlarm.saveEqAlarmList1000(etlConfD,saveList);
                saveEqAlarm.deleteEqAlarmList1000(etlConfD);
            }

        }

        resMsg[0]=String.valueOf(okCnt);
        resMsg[1]=String.valueOf(errCnt);
        resMsg[2]=errMsg;

        return resMsg;
    }


    public List<String> getEqpts(EtlConfD etlConfD){
        List<String> eqpts=new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start=etlConfD.getRunStartTimestamp().toString().substring(0,19);
        String end=etlConfD.getRunEndTimestamp().toString().substring(0,19);

        try {
            String sql = "select " +
                    " DISTINCT unitname as equipId" +
                    " from mes_ct_machinealarmhistory " +
                    " where 1=1" +
                    " and UPDATETIME >= to_date('" + start + "','yyyy-mm-dd hh24:mi:ss') " +
                    " AND UPDATETIME <  to_date('" + end + "','yyyy-mm-dd hh24:mi:ss')";
            eqpts = mesdao.findBySQL(sql);
            if(eqpts.isEmpty()) eqpts.add(null);
        }catch (Exception e){
            logger.error(LoggerUtil.stackTraceToString(e));
        }
        return eqpts;
    }
}
